package com.opdar.platform.gateway.point;

import com.opdar.platform.utils.MD5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by shiju on 2017/12/14.
 */
public class PointProxy implements MethodInterceptor {

    public static Class<?> getProxyClass(Class clazz) {
        //设置需要创建子类的类
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallbackType(PointProxy.class);
        return enhancer.createClass();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        StackTraceElement stack = Thread.currentThread().getStackTrace()[3];
        String className = stack.getClassName();
        int lineNumber = stack.getLineNumber();
        String methodName = stack.getMethodName();
        String code = MD5.encrypt(className + methodName + lineNumber);
        PointManager.setCurrentCode(code);
        Object object = null;
        try{
            object = methodProxy.invokeSuper(o, objects);
        } finally {
            PointManager.clearCurrentCode();
        }
        return object;
    }
}
